package com.myprinciple.singleton.type7;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/4/10 16:57
 */
public class SingletonTest07 {

    public static void main(String[] args) {
        System.out.println("使用静态内部类完成单例模式");
        // 测试
        Singleton instance = Singleton.getInstance();
        Singleton instance1 = Singleton.getInstance();
        // true 表示两个对象为同一个引用 
        System.out.println(instance1 == instance);
        System.out.println("instance.hashCode() = " + instance.hashCode());
        System.out.println("instance1.hashCode() = " + instance1.hashCode());
    }
    
}

// 静态内部类完成
class Singleton {
    // 构造器私有化
    private Singleton() {}

    // 写一个静态内部类，该类中有一个静态属性 Singleton
    private static class SingletonInstance {
        private static final Singleton INSTANCE = new Singleton();
    }
    
    // 提供一个静态的公有方法，直接返回SingletonInstance.INSTANCE
    public static Singleton getInstance(){
        return SingletonInstance.INSTANCE;
    }
}
